<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :class="{hasImg:fileList.length>0}"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowPercent" :text-inside="true" :stroke-width="26" :percentage="percent" style="width:146px" />
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img :src="previewImg" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDPcYEdka8QWLtAAtKWR5SYNvCCvNaWBZg',
  SecretKey: 'rRklVyA5j6C2e3B2cvwkHYXGitnPrSnq'
})
export default {
  props: {
    imgUrl: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      percent: 0,
      fileList: [],
      isShowDialog: false,
      isShowPercent: false,
      previewImg: ''
    }
  },
  watch: {
    imgUrl() {
      console.log(666)
      if (this.imgUrl) {
        this.fileList = [{
          url: this.imgUrl
        }]
      }
    }
  },
  methods: {
    onPreview(file) {
      this.isShowDialog = true
      this.previewImg = file.url
    },
    onRemove(file, newFileList) {
      console.log(file, newFileList)
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      console.log(50, file, newFileList)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      const typeList = ['image/jpeg', 'image/png', 'image/gif']
      if (!typeList.includes(file.type)) {
        this.$message.error('目前只支持jpeg/png/gif样式的图片哦')
        return false
      }
      const maxSize = 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片不能超过1M')
        return false
      }
    },
    httpRequest(params) {
      this.isShowPercent = true
      console.log(params)
      cos.putObject({
        Bucket: 'hr-71-1309641470', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(56, JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        setTimeout(() => {
          this.isShowPercent = false
        }, 1000)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.hasImg{
::v-deep .el-upload--picture-card{
  display: none;
}
}
</style>
